import React, { type ReactNode } from 'react'
import {Breadcrumb} from 'antd';
import { useSelector } from 'react-redux';
import { useLocation,useNavigate } from 'react-router-dom';

interface MenuItem {
  key: string;
  label: string;
  icon?: string;
  children?: MenuItem[];
}

interface BreadcrumbItem {
  title: string | ReactNode;
}

// 递归查找菜单项及其路径
function findMenuItemAndPath(path: string, menu: MenuItem[]): { item: MenuItem | null, path: MenuItem[] } {
  for (const item of menu) {
    if (item.key === path) {
      return { item, path: [item] };
    }
    
    if (item.children && item.children.length > 0) {
      const result = findMenuItemAndPath(path, item.children);
      if (result.item) {
        return { item: result.item, path: [item, ...result.path] };
      }
    }
  }
  
  return { item: null, path: [] };
}

// 生成面包屑项
function generateBreadcrumbItems(menuPath: MenuItem[], navigate: any): BreadcrumbItem[] {
  return menuPath.map((item, index) => {
    // 第一项（首页）不可点击，最后一项（当前页面）也不可点击
    if (index === 0 || index === menuPath.length - 1) {
      return {
        title: item.label
      };
    }
    
    // 中间项可点击
    return {
      title: (
        <span 
          onClick={() => navigate(item.key)} 
          style={{ cursor: 'pointer', color: '#1890ff' }}
        >
          {item.label}
        </span>
      )
    };
  });
}

export default function MyBreadcrumb() {
  const { menuList } = useSelector((state: any) => state.userReducer);
  const location = useLocation();
  const navigate = useNavigate();
  
  // 获取当前路径对应的菜单项及其完整路径
  const { item, path } = findMenuItemAndPath(location.pathname, menuList);
  
  // 生成面包屑项
  const breadcrumbItems = item ? generateBreadcrumbItems(path, navigate) : [];
  
  return (
    <Breadcrumb
      items={breadcrumbItems}
    />
  );
}